const api = require('../../../../ws_micro_shop/utils/api.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const utils = require('../../../../ws_micro_shop/utils/utils.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

Page({
  data: {
    groupFail: 0,
    show_attr_picker: false,
    form: {
      number: 1,
    },
    theme: app.themeData,
    unit: '',
    imgUrl: app.imgUrl,
    show_rule: false,
  },
  onLoad(opt) {
    let options = opt || {};
    let parent_id = 0;
    let shop_id = 0;
    let share_scene = '';
    let user_id = options.user_id;
    let scene = decodeURIComponent(options.scene);
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
    })
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
      shop_id = options.shopid;
    }
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    app.pageOnLoad(this);
    let userinfo = wx.getStorageSync('user_info');
    let that = this;
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    if (user_id) {
      parent_id = user_id;
      share_scene = 4;
    } else if (scene) {
      let scene_obj = utils.scene_decode(scene);
      if (scene_obj.uid && scene_obj.oid) {
        parent_id = scene_obj.uid;
        options.oid = scene_obj.oid;
        shop_id = scene_obj.sid;
        app.ws_micro_shop_globalData.shopid = scene_obj.sid;
      } else {
        parent_id = scene;
      }
      share_scene = 6;
    }
    parent_id && (app.ws_micro_shop_globalData.parent_id = parent_id);
    if (userinfo) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      app.loginBindParent({
        parent_id,
        shop_id,
        share_scene,
      });
      this.getInfo(options);
      util.prepareBindInfo(options, moduleName, that);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
        app.getStoreData().then(res => {
          app.loginBindParent({
            parent_id,
            shop_id,
            share_scene,
          });
        });
        that.getInfo(options);
      });
    }
    this.setData({
      oid: options.oid,
      opts: options,
      isSaas: app.ws_micro_shop_globalData.isSaas
    });
  },
  onShareAppMessage() {
    let user_info = wx.getStorageSync('user_info');
    let path = '/ws_micro_shop_pt/pages/pt/group/details?oid=' + this.data.oid + '&user_id=' + user_info.id + '&tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid;
    path = util.spliceSharePath(path, '4', moduleName);
    return {
      title: '快来' + this.data.unit + this.data.goods.price + '拼  ' + this.data.goods.name,
      path,
      imageUrl: this.data.goods.cover_pic
    };
  },
  onShareTimeline() {
    let user_info = wx.getStorageSync('user_info');
    return {
      title: '快来' + this.data.unit + this.data.goods.price + '拼  ' + this.data.goods.name,
      imageUrl: this.data.goods.cover_pic,
      query: 'oid=' + this.data.oid + '&user_id=' + user_info.id + '&tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid
    }
  },
  onHide() {
    util.sendBindInfo(this.data);
  },
  onUnload() {
    util.sendBindInfo(this.data);
  },
  getInfo(e) {
    let oid = e.oid;
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.group_info,
      method: 'GET',
      data: {
        oid,
      },
      success: function (res) {
        if (res.code === 0) {
          if (Number(res.data.groupFail) === 0) {
            that.countDownRun(res.data.limit_time_ms);
          }
          let reduce_price = (res.data.goods.original_price - res.data.goods.price).toFixed(2);
          that.setData({
            goods: res.data.goods,
            groupList: res.data.groupList,
            surplus: res.data.surplus,
            limit_time_ms: res.data.limit_time_ms,
            goods_list: res.data.goodsList,
            group_fail: res.data.groupFail,
            oid: res.data.oid,
            in_group: res.data.inGroup,
            attr_group_list: res.data.attr_group_list,
            group_rule_id: res.data.groupRuleId,
            reduce_price: reduce_price < 0 ? 0 : reduce_price,
            virtual_sales: res.data.virtual_sales,
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                app.util.navigateTo('/ws_micro_shop_pt/pages/pt/index/index', {}, true);
              }
            },
          });
        }
      },
      complete: function () {
        setTimeout(function () {
          wx.hideLoading();
        }, 1000);
      },
    });
  },
  countDownRun(limit_time_ms) {
    let that = this;
    setInterval(function () {
      let leftTime = (new Date(limit_time_ms[0], limit_time_ms[1] - 1, limit_time_ms[2], limit_time_ms[3], limit_time_ms[4], limit_time_ms[5])) - (new Date());
      let days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10);
      let hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10);
      let minutes = parseInt(leftTime / 1000 / 60 % 60, 10);
      let seconds = parseInt(leftTime / 1000 % 60, 10);
      days = that.checkTime(days);
      hours = that.checkTime(hours);
      minutes = that.checkTime(minutes);
      seconds = that.checkTime(seconds);
      that.setData({
        limit_time: {
          days: days,
          hours: hours,
          mins: minutes,
          secs: seconds,
        },
      });
    }, 1000);
  },
  checkTime: function (paramI) {
    let i = paramI;
    i = i > 0 ? i : 0;
    if (i < 10) {
      i = '0' + i;
    }
    return i;
  },
  goToHome() {
    app.util.navigateTo('/ws_micro_shop_pt/pages/pt/index/index', {}, true);
  },
  goToGoodsDetails() {
    wx.redirectTo({
      url: '/ws_micro_shop_pt/pages/pt/details/details?gid=' + this.data.goods.id,
    });
  },
  hideAttrPicker() {
    this.setData({
      show_attr_picker: false,
    });
  },
  showAttrPicker() {
    this.setData({
      show_attr_picker: true,
    });
  },
  attrClick(e) {
    let that = this;
    let attr_group_id = Number(e.currentTarget.dataset.groupId);
    let attr_id = Number(e.currentTarget.dataset.id);
    let attr_group_list = that.data.attr_group_list;
    for (let i in attr_group_list) {
      if (Number(attr_group_list[i].attr_group_id) !== attr_group_id) { continue }
      for (let j in attr_group_list[i].attr_list) {
        if (Number(attr_group_list[i].attr_list[j].attr_id) === attr_id) {
          attr_group_list[i].attr_list[j].checked = true;
        } else {
          attr_group_list[i].attr_list[j].checked = false;
        }
      }
    }
    that.setData({
      attr_group_list: attr_group_list,
    });
    let check_attr_list = [];
    let check_all = true;
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let group_checked = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            check_attr_list.push(attr_group_list[i].attr_list[j].attr_id);
            group_checked = true;
            break;
          }
        }
        if (!group_checked) {
          check_all = false;
          break;
        }
      }
    }
    if (!check_all) {
      return;
    }
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.goods_attr_info,
      data: {
        goods_id: that.data.goods.id,
        attr_list: JSON.stringify(check_attr_list),
      },
      success: function (res) {
        wx.hideLoading();
        if (res.code === 0) {
          let goods = that.data.goods;
          goods.price = res.data.price;
          goods.num = res.data.num;
          goods.attr_pic = res.data.pic;
          that.setData({
            goods,
          });
        }
      },
    });
  },
  buyNow() {
    this.submit('GROUP_BUY_C');
  },
  submit(type) {
    if (!this.data.show_attr_picker) {
      this.setData({
        show_attr_picker: true,
      });
      return true;
    }
    if (this.data.form.number > this.data.goods.num) {
      wx.showToast({
        title: '商品库存不足，请选择其它规格或数量',
        icon: 'none',
      });
      return true;
    }
    let attr_group_list = this.data.attr_group_list;
    let checked_attr_list = [];
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let attr = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            attr = {
              attr_id: attr_group_list[i].attr_list[j].attr_id,
              attr_name: attr_group_list[i].attr_list[j].attr_name,
            };
            break;
          }
        }
        if (!attr) {
          wx.showToast({
            title: '请选择' + attr_group_list[i].attr_group_name,
            icon: 'none',
          });
          return true;
        } else {
          checked_attr_list.push({
            attr_group_id: attr_group_list[i].attr_group_id,
            attr_group_name: attr_group_list[i].attr_group_name,
            attr_id: attr.attr_id,
            attr_name: attr.attr_name,
          });
        }
      }
    }
    this.setData({
      show_attr_picker: false,
    });
    wx.redirectTo({
      url: '/ws_micro_shop_pt/pages/pt/order-submit/order-submit?goods_info=' + JSON.stringify({
        goods_id: this.data.goods.id,
        attr: checked_attr_list,
        num: this.data.form.number,
        type: type,
        parent_id: this.data.oid,
        deliver_type: this.data.goods.type,
      }),
    });
  },
  numberSub() {
    let num = this.data.form.number;
    if (num <= 1) {
      return true;
    }
    num--;
    this.setData({
      form: {
        number: num,
      },
    });
  },
  numberAdd() {
    let num = this.data.form.number;
    num++;
    if (Number(this.data.goods.one_buy_limit) === 0) {
      this.setData({
        form: {
          number: num,
        },
      });
    } else {
      if (num > this.data.goods.one_buy_limit) {
        wx.showModal({
          title: '提示',
          content: '最多只允许购买' + this.data.goods.one_buy_limit + '件',
          showCancel: false,
        });
        this.setData({
          form: {
            number: num - 1,
          },
        });
      } else {
        this.setData({
          form: {
            number: num,
          },
        });
      }
    }
  },
  numberBlur(e) {
    let num = e.detail.value;
    num = parseInt(num, 10);
    if (isNaN(num)) { num = 1 }
    if (num <= 0) { num = 1 }
    if (Number(this.data.goods.one_buy_limit) === 0) {
      this.setData({
        form: {
          number: num,
        },
      });
    } else {
      if (num > this.data.goods.one_buy_limit) {
        wx.showModal({
          title: '提示',
          content: '最多只允许购买' + this.data.goods.one_buy_limit + '件',
          showCancel: false,
        });
        this.setData({
          form: {
            number: this.data.goods.one_buy_limit,
          },
        });
      } else {
        this.setData({
          form: {
            number: num,
          },
        });
      }
    }
  },
  showShareModal() {
    this.setData({
      share_modal_active: 'active',
    });
  },
  shareModalClose() {
    this.setData({
      share_modal_active: '',
    });
  },
  getGoodsQrcode() {
    let that = this;
    that.setData({
      goods_qrcode_active: 'active',
      share_modal_active: '',
    });
    if (that.data.goods_qrcode) {
      return true;
    }
    app.ws_micro_shoprequest({
      url: api.group.order.goods_qrcode,
      data: {
        order_id: that.data.oid,
      },
      success: function (res) {
        if (res.code === 0) {
          that.setData({
            goods_qrcode: res.data.pic_url,
          });
        }
        if (res.code === 1) {
          that.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
    });
  },
  saveGoodsQrcode() {
    let that = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.showLoading({
      title: '正在保存图片',
      mask: false,
    });
    wx.downloadFile({
      url: that.data.goods_qrcode,
      success: function (e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: false,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function () {
            wx.showModal({
              title: '提示',
              content: '商品海报保存成功',
              showCancel: false,
            });
          },
          fail: function (e) {
            wx.showModal({
              title: '图片保存失败',
              content: e.errMsg,
              showCancel: false,
            });
          },
          complete: function () {
            wx.hideLoading();
          },
        });
      },
      fail: function (e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + that.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },
  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  disabledClick() {
    // it`s necessnary
  },
  shareModalClose() {
    this.setData({
      share_modal_active: '',
    });
  },
  onNavigate(e) {
    let param = e.currentTarget.dataset;
    app.ws_micro_shop_navigate(param);
  },
  goArticle(e) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.article_detail,
      data: {
        id: that.data.group_rule_id,
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            content: res.data.content,
            show_rule: true,
      });
    }
      },
    });
  },
  closeRule() {
    this.setData({
      show_rule: false,
    })
  },
  disabledClick() {
    // it`s necessary
  },

});
